"""
1. 验证认证逻辑
2. 展示效果逻辑
"""

from rest_framework import serializers
from .models import Article, Profile
from django.contrib.auth import get_user_model

User = get_user_model()  # 获取用户模型


# class ArticleSerializer(serializers.Serializer):
#     # 只读
#     id = serializers.IntegerField(read_only=True)
#     create_date = serializers.DateTimeField(read_only=True)
#
#     author = serializers.ReadOnlyField(source="author.id")  # TODO 这个位置没看懂 ？-->  author我们也希望在视图中与request.user 绑定
#     # serializer.save(author=request.user) 由auther是只读的， 需要通过手动这样子和当前用户帮定
#
#     # 可以用户添加修改
#     status = serializers.ChoiceField(choices=Article.STATUS_CHOICES, default='p')
#     body = serializers.CharField(required=False, allow_blank=True)
#     title = serializers.CharField(required=True, allow_blank=True, max_length=90)
#
#     def create(self, validated_data):
#         """
#         Create a new "article" instance
#         """
#         return Article.objects.create(**validated_data)
#
#     def update(self, instance, validated_data):
#         """
#         Use validated data to return an existing `Article`instance。"""
#         instance.title = validated_data.get('title', instance.title)
#         instance.body = validated_data.get('body', instance.body)
#         instance.status = validated_data.get('status', instance.status)
#         instance.save()
#         return instance

# # ？ 与上面等价
# class ArticleSerializer(serializers.ModelSerializer):
#
#     # author = serializers.HiddenField(default=serializers.CurrentUserDefault()) # todo 与当前用户绑定
#     author = serializers.ReadOnlyField(source="author.username")
#
#     class Meta:
#         model = Article
#         fields = '__all__'
#         read_only_fields = ('id',  'create_date')


class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('mobile',)  # 写all会陷入一个死循环

    def validate_mobile(self, mobile):
        if len(mobile) != 11:
            raise serializers.ValidationError("电话号码不等于11位")
        return mobile


class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(read_only=True)  # todo 这样子会报错， 关联查询的时候除了问题

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'profile')

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = User.objects.create(**validated_data)
        Profile.objects.create(user=user, **profile_data)
        return user


class ArticleSerializer(serializers.ModelSerializer):
    # author = serializers.ReadOnlyField(source="author.username")
    author = UserSerializer(read_only=True, )  # 即使我们在 read_only_fields 设置了, 但是他覆盖了， 所以还要写一次

    # author123 = serializers.ReadOnlyField(source="author.username") # 后面指定source就行了 author123 只决定了给前端显示什么， 如果创建还算要 author
    status = serializers.ChoiceField(source="get_status_display", choices=Article.STATUS_CHOICES, default='p')

    # liked_by = serializers.ManyRelatedField(source='liked_by.name')

    cn_status = serializers.SerializerMethodField()

    class Meta:
        model = Article
        fields = '__all__'
        read_only_fields = ('id', 'create_date', 'author')

    def get_cn_status(self, obj):
        if obj.status == 'p':
            return "已发表"
        elif obj.status == 'd':
            return "草稿"
        else:
            return ''

    def to_representation(self, instance):
        # 调用父类获取当前序列化数据，value代表每个对象实例obj
        data = super().to_representation(instance)
        # 对序列化数据做修改，添加新的数据
        data['total_likes'] = instance.liked_by.count()
        return data

    def validate(self, data):
        """

        :param data:  用于创建和更新，传入的字典数据
        :return:
        """
        # if data['start'] > data['finish']:
        #     raise serializers.ValidationError("finish must occur after start")
        return data
